<template>
  <div class="app-container">
    <div class="app-container__section" >
      <PlusSearch
        v-bind="getSearchBinds()"
        :columns="columns"
        v-model="searchForm"
      >
      </PlusSearch>
    </div>
    <div class="app-container__section">
      <PlusTable
        v-bind="getBinds()"
        :columns="columns"
      >
        <template #title>
          <table-title />
        </template>
        <template #toolbar>
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:config:add']">新增</el-button>
          <el-button type="success" plain icon="Edit" :disabled="gSelection.length !== 1" @click="handleUpdate" v-hasPermi="['system:config:edit']">修改</el-button>
          <el-button type="danger" plain icon="Delete" :disabled="gSelection.length === 0" @click="handleDelete" v-hasPermi="['system:config:remove']">删除</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:config:export']">导出</el-button>
          <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache" v-hasPermi="['system:config:remove']">刷新缓存</el-button>
          <ClockTimer :task="gGetList" />
          <SearchAreaControl v-model="gShowSearchForm" />
        </template>
        <template #plus-cell-status="scope">
          <dict-tag  :options="sys_yes_no" :value="scope.row.configType"></dict-tag>
        </template>
        <template #plus-cell-action="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:config:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:config:remove']">删除</el-button>
        </template>
      </PlusTable>
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="configRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="form.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="form.configValue" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item prop="configType">
          <template #label>
            <el-tooltip effect="dark" content="系统内置，代表该行配置不可删除，是代表不可删除，否代表可以删除" placement="top-start">
              <div class="tips">
                <QuestionFilled class="tips-icon" :size="'14px'" />
              </div>
            </el-tooltip>
            <span style="width: 80px">系统内置</span>
          </template>
          <el-radio-group v-model="form.configType">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Config">
import { listConfig, getConfig, delConfig, addConfig, updateConfig, refreshCache } from '@/api/system/config'
import { PlusSearch, PlusTable } from 'plus-pro-components'
import { useTablePage } from '@/hooks/useTablePage.js'
import { useActions } from '@/hooks/useActions.js'
const { proxy } = getCurrentInstance()
const { sys_yes_no } = proxy.useDict('sys_yes_no')

// =============================================
const columns = computed(()=>[
  {
    label: '参数主键',
    prop: 'configId',
    hideInSearch: true,
    tableColumnProps: {
      align: 'center'
    },
  },
  {
    label: '参数名称',
    prop: 'configName',
    tableColumnProps: {
      align: 'center'
    },
  },
  {
    label: '参数键名',
    prop: 'configKey',
    tableColumnProps: {
      align: 'center'
    },
  },
  {
    label: '系统内置',
    prop: 'configType',
    tableColumnProps: {
      align: 'center'
    },
    valueType: 'select',
    options: sys_yes_no.value,
  },
  {
    label: '备注',
    prop: 'remark',
    hideInSearch: true,
    tableColumnProps: {
      align: 'center'
    },
  },
  {
    label: '创建时间',
    prop: 'createTime',
    hideInSearch: true,
    tableColumnProps: {
      align: 'center'
    },
    valueType:'date-picker',
    fieldProps: {
      type: 'daterange',
      valueFormat: "YYYY-MM-DD"
    },
  },
  {
    label: '操作',
    prop: 'action',
    width: '160px',
    hideInSearch: true,
    tableColumnProps: {
      align: 'center',
      fixed:'right'
    }
  },
])

// 搜索条件
const searchForm = ref({})

const {
  gRouteMeta,
  gTableData,
  gTotal,
  gLoadingStatus,
  gPageInfo,
  gReset,
  gGetList,
  gOnPageChange,
  gSelection,
  gOnSelectionChange,
  gShowSearchForm,
  gResetForm,
  gResetPage,
  getBinds,
  getSearchBinds
} = useTablePage(listConfig, {
  searchForm,
})


const { deleteAction } = useActions();
function handleDelete(row) {
  deleteAction({
    api: delConfig,
    uniqueKey:'configId',
    selection: row.configId || gSelection.value
  }).then(() => {
    gGetList();
  });
}

// =============================================

const open = ref(false)
const title = ref('')

const data = reactive({
  form: {},
  rules: {
    configName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
    configKey: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
    configValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }]
  }
})

const {  form, rules } = toRefs(data)
/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}
/** 表单重置 */
function reset() {
  form.value = {
    configId: undefined,
    configName: undefined,
    configKey: undefined,
    configValue: undefined,
    configType: 'Y',
    remark: undefined
  }
  proxy.resetForm('configRef')
}
/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加参数'
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const configId = row.configId || gSelection.value[0].configId
  getConfig(configId).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改参数'
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['configRef'].validate((valid) => {
    if (valid) {
      if (form.value.configId != undefined) {
        updateConfig(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          gGetList()
        })
      } else {
        addConfig(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          gGetList()
        })
      }
    }
  })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/config/export',
    {
      ...searchForm.value
    },
    `config_${new Date().getTime()}.xlsx`
  )
}
/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  refreshCache().then(() => {
    proxy.$modal.msgSuccess('刷新缓存成功')
  })
}
</script>
